package com.lzs.common.utils.wechat;

import java.util.Arrays;

/**
 * byte[]与16进制字符串相互转换
 *
 */
public class BytesHexStrTranslate {

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 方法二：
     * byte[] to hex string
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        char[] buf = new char[bytes.length * 2];
        int index = 0;
        for(byte b : bytes) { // 利用位运算进行转换，可以看作方法一的变种
            buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
            buf[index++] = HEX_CHAR[b & 0xf];
        }

        return new String(buf);
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }
        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }

//    public static void main(String[] args) throws Exception {
//        byte[] bytes = "测试".getBytes("utf-8");
//        System.out.println("字节数组为：" + Arrays.toString(bytes));
//        System.out.println("方法一：" + bytesToHex(bytes));
//
//        System.out.println("==================================");
//
//        String str = "e6b58be8af95";
//        System.out.println("转换后的字节数组：" + Arrays.toString(toBytes(str)));
//        System.out.println(new String(toBytes(str), "utf-8"));
//    }

}
